#!/usr/bin/env python -OO
# -*- coding: utf-8 -*-

# Copyright © 2008,2009 Trust Digital Technology Laboratory, Shanghai Jiao Tong University.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author:
#   XING Dong sheng <homer.xing@gmail.com>

# sudo apt-get install python-xlib -y

import sys, os
import time
try:
	import Xlib
except:
	import os
	print "Run 'sudo apt-get install python-xlib -y'"
	os.system('sudo apt-get install python-xlib -y')
	try:
		import Xlib
	except:
		sys.exit(0)
import Xlib.display

def onerror(a,b):
	print a,b,"Error!"

def find(dpy, window, wmname):
	W = window.get_wm_name()
	if wmname==None:
		if W!=None and len(W.strip())!=0: print W.strip()
		return False
	elif wmname==W:
		return True

def found(dpy, window, wmname):
	List=window.query_tree()
	for child_window in List.children:
		if find(dpy, child_window, wmname):
			return True
		if found(dpy, child_window, wmname):
			return True
	return False

def waitwindow(wmname=None):
	displayname = ":0.0" #arg
	
	while True:
		dpy=Xlib.display.Display(displayname)
		if dpy==0:
			print "Error in Xlib.display.Display(%s)!"%displayname
			sys.exit(0)

		for i in range(0, dpy.screen_count()):
			if found(dpy, dpy.screen(i).root, wmname):
				dpy.close()
				return True
		
		dpy.close()
		if wmname==None: return False
		else: time.sleep(2)

if __name__ == "__main__":
	waitwindow() #列出全部窗口的wmname
